/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.service.im;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.server.common.utils.MD5Utils;
import com.server.common.utils.UUIDUtils;
import com.server.modules.api.service.IMService;
import com.server.modules.sys.dao.UserDao;
import com.server.modules.sys.dao.hxchatrecord.HxChatRecordSynclogDao;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.hxchatrecord.HxChatRecord;
import com.server.modules.sys.entity.hxchatrecord.HxChatRecordSynclog;
import com.server.modules.sys.service.SystemService;
import com.server.modules.sys.service.hxchatrecord.HxChatRecordService;
import com.server.modules.sys.utils.Base64Utils;

@Service("ImService2")
@Transactional(readOnly = true)
public class ImService  {
	private static final String String = null;
	@Resource
    protected IMService imService;
	@Resource
    protected SystemService systemService;
	@Resource
	private UserDao userDao;
	@Resource
	private HxChatRecordService hxChatRecordService;
	
	@Resource
	private HxChatRecordSynclogDao hxChatRecordSynclogDao;
	
	@Transactional(readOnly = false)
	public Object batchRegisterUnHxUsers() throws Exception{
		List<User> users = systemService.getUnHxUser();
		 List<Map<String, Object>> list = new ArrayList<>();
		 for (User u : users) {
			Map<String, Object> param = new HashMap<String, Object>();
			u.setHxUsername(UUIDUtils.getUUID() );
			u.setHxPassword(MD5Utils.md5Encode(u.getHxUsername()));
			param.put("username",u.getHxUsername());
	        param.put("password",u.getHxPassword());
	        param.put("nickname",u.getName());
	        list.add(param);
		}
		 //环信一次请求只支持5kb 还是要分批去注册
		 int k = 0;
		 Map createNewIMUserBatch=null;
		 for (int i = 0; i < list.size(); i+=15) {
			 List  newlist =null;
			 List<User>   newUserlist =null;
			 if(i+14>=list.size()){
				   newlist = list.subList(i,list.size());
				   newUserlist=users.subList(i,list.size());
			 }else{
				   newlist = list.subList(i,i+15); 
				   newUserlist=users.subList(i,i+15);
			 }
			  createNewIMUserBatch = imService.createNewIMUserBatch(newlist);
				if(createNewIMUserBatch.containsKey("statusCode")){
					Object object = createNewIMUserBatch.get("statusCode");
					Integer state=(Integer) object;
					if(state==200){
						for (int j = 0; j < newUserlist.size(); j++) {
							User user = newUserlist.get(j);
							userDao.update(user);
						}	
					}
				}
			 k++;
		 }
		return createNewIMUserBatch;
	}
	
	

	private void fetchChatRecord(long currentTimeMillis,List<HxChatRecord> list,String cursor1) {
		Map ret = imService.queryChatMessages(currentTimeMillis, 100l, cursor1,">");
		if(ret!=null){
			Integer statusCode=(Integer) ret.get("statusCode");
			//获取同步数据成功
			if(statusCode==200){
				//获取短信内容
				String cursor = (String) ret.get("cursor");
				List<Map<String,Object>> object = (List<Map<String, Object>>) ret.get("entities");
				for (Map<String, Object> map : object) {
					HxChatRecord chatRecord=new HxChatRecord();
					chatRecord.setToHxusername((String) map.get("to"));
					Long timestamp = (Long) map.get("timestamp");
					Date date = new Date(timestamp);
					chatRecord.setSendTime(date);
					chatRecord.setSendTimeMs(timestamp);
					chatRecord.setMsgId((String) map.get("msg_id"));
					Map<String,Object> payload =(Map<String, Object>) map.get("payload");
					List<Map<String, Object>> bodies = (List<Map<String, Object>>) payload.get("bodies");
					Map<String, Object> msgBody = bodies.get(0);
					String msg=(String) msgBody.get("msg");
					chatRecord.setMsg(Base64Utils.encode(msg));
					chatRecord.setType((String) msgBody.get("type"));
					chatRecord.setLength((String) msgBody.get("length"));
					chatRecord.setUrl((String) msgBody.get("url"));
					chatRecord.setFilename((String) msgBody.get("filename"));
					chatRecord.setSecret((String) msgBody.get("secret"));
					Object lat = msgBody.get("lat");
					if(lat!=null){
						if(lat instanceof BigDecimal){
							chatRecord.setLat(((BigDecimal) lat).toString());
						}else{
							chatRecord.setLat(lat.toString());
						}
					}
					Object lng = msgBody.get("lng");
					if(lng!=null){
						if(lng instanceof BigDecimal){
							chatRecord.setLng(((BigDecimal) lng).toString());
						}else{
							chatRecord.setLng(lng.toString());
						}
					}
					
					chatRecord.setAddr((String) msgBody.get("addr"));
					chatRecord.setThumb((String) msgBody.get("thumb"));
					chatRecord.setThumbSecret((String) msgBody.get("thumb_secret"));
					chatRecord.setFileLength((Long) msgBody.get("file_length"));
					if(bodies.size()>1){
						Map<String, Object> extBody = bodies.get(1);
						chatRecord.setExt((String) extBody.get("ext"));
					}
					chatRecord.setFromHxusername((String) map.get("from"));
					chatRecord.setChatType((String) map.get("chat_type"));
					list.add(chatRecord);
				}
				if(StringUtils.isNotBlank(cursor)){
					HxChatRecord hxChatRecord = list.get(list.size()-1);
					Date sendTime = hxChatRecord.getSendTime();
					 fetchChatRecord(sendTime.getTime(),list,cursor);
				}
			}
		}
	}
	@Transactional(readOnly = false)
	public void  synchronizeChatRecordToDbByLastSendTime(){
		try {
			List<HxChatRecord> all = hxChatRecordService.findList(new HxChatRecord());
			if(CollectionUtils.isEmpty(all)){
				Integer count = synchronizeAllChatRecordFromHx();
				HxChatRecordSynclog log=new HxChatRecordSynclog();
				log.preInsert();
				log.setSuccessFlag(true);
				log.setRemarks("系统定时同步");
				log.setSyncCount(new Long(count));
				hxChatRecordSynclogDao.insert(log);
			}else{
				HxChatRecord hxChatRecord = all.get(all.size()-1);
				Long sendTime = hxChatRecord.getSendTimeMs();
				List<HxChatRecord> list=new ArrayList<>();
				this.fetchChatRecord(sendTime, list, null);
				if(!CollectionUtils.isEmpty(list)){
					for (HxChatRecord hxChatRecord2 : list) {
						hxChatRecordService.save(hxChatRecord2);
					}
					HxChatRecordSynclog log=new HxChatRecordSynclog();
					log.preInsert();
					log.setSuccessFlag(true);
					log.setRemarks("系统定时同步");
					log.setSyncCount(new Long(list.size()));
					hxChatRecordSynclogDao.insert(log);
				}
			}
		} catch (Exception e) {
			HxChatRecordSynclog log=new HxChatRecordSynclog();
			log.preInsert();
			log.setSuccessFlag(false);
			log.setSyncCount(new Long(0));
			log.setRemarks("系统定时同步");
			hxChatRecordSynclogDao.insert(log);
		}
	}
	@Transactional(readOnly = false)
	public Integer  synchronizeAllChatRecordFromHx(){
		Date date = new Date();
		date.setTime(1403164734226l);
		List<HxChatRecord> list=new ArrayList<>();
		 fetchChatRecord(date.getTime(),list,null);
		 for (HxChatRecord hxChatRecord : list) {
			 hxChatRecordService.save(hxChatRecord);
		}
		return list.size();
	}
	
	public List<HxChatRecord>  getChatRecordByToAndFrom(String to,String from){
		HxChatRecord hxChatRecord=new HxChatRecord();
		hxChatRecord.setToHxusername(to);
		hxChatRecord.setFromHxusername(from);
		List<HxChatRecord> findList = hxChatRecordService.findList(hxChatRecord);
		for (HxChatRecord hxChatRecord2 : findList) {
			hxChatRecord2.setMsg(Base64Utils.decode(hxChatRecord2.getMsg()));
		}
		return hxChatRecordService.findList(hxChatRecord);
	}



	public Object getChatRecordFromHx() {
		List<HxChatRecord> all = hxChatRecordService.findList(new HxChatRecord());
		if(CollectionUtils.isEmpty(all)){
			synchronizeAllChatRecordFromHx();
		}else{
			HxChatRecord hxChatRecord = all.get(all.size()-1);
			
			Date sendTime = hxChatRecord.getSendTime();
			List<HxChatRecord> list=new ArrayList<>();
			 this.fetchChatRecord(sendTime.getTime(), list, null);
			 HxChatRecord hxChatRecord2 = list.get(0);
			 return list;
			
		}
		return null;
	}
	
	
	
}
